#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Python 3.x
Flask 2.1.3
Flask-Mail 0.9.1

Official Manual Address : https://pythonhosted.org/Flask-Mail/

"""

from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)

# Mail Configure
app.config['MAIL_SERVER'] = 'localhost'
app.config['MAIL_HOST'] = 25
app.config['MAIL_USERNAME'] = 'you mail username'
app.config['MAIL_PASSWORD'] = 'you mail password'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

# Initialize the mail object
mail = Mail(app=app)


@app.route('/send_mail')
def send_mail():
    """
    Send Mail
    :return:
    """
    # 如邮件配置MAIL_DEFAULT_SENDER设置默认发件人，那么初始化Message时不必指定sender
    msg = Message(sender='form@example.com', recipients=['to@exmaple.com'])
    # 设置发件人别名
    msg2 = Message(sender=('Me', 'form@example.com'), recipients=['to@exmaple.com'])
    # 指定邮件标题
    msg.subject = 'testing title'
    # 指定邮件正文内容（文本/html）
    msg.body = 'testing'  # 纯文本消息
    msg.html = '<b>testing<b>'  # Html消息
    # 发送邮件
    mail.send(msg)
    return '发送邮件'


@app.route('/send_batch_mail')
def send_batch_mail():
    """
    批量发送邮件
    """
    # 与电子邮件服务器的连接会一直保持活动状态直到所有的邮件都已经发送完成才会关闭连接
    # ※有些邮件服务器会限制一次连接中的发送邮件上线。可以设置重连前的发送邮件的最大数，通过配置MAIL_MAX_EMAILS
    users = [{
        "name": "",
        "mail": ""
    }]
    with mail.connect() as conn:
        for user in users:
            message = "...."
            subject = "hello, %s" % user["name"]
            msg = Message(recipients=[user["mail"]], body=message, subject=subject)
            conn.send(message=msg)
    return '批量发送邮件'


@app.route('/send_attachment_mail')
def send_attachment_mail():
    """
    发送附件邮件
    """
    msg = Message(sender='form@example.com', recipients=['to@exmaple.com'])
    msg.subject = 'testing title'
    msg.body = 'testing'

    with app.open_resource("image.png") as fp:
        # 如果 MAIL_ASCII_ATTACHMENTS 设置成 True 的话，文件名将会转换成 ASCII 的。
        msg.attach(filename="image.png", content_type="image/png", data=fp.read)
    mail.send(msg)
    return '发送附件邮件'


if __name__ == '__main__':
    app.run()
